/*
 * FeedBackView.java
 */
package feedback;

import XML.XmlConfig;
import XML.XmlModul;
import db.ConnectionProperties;
import db.definitions.ColumnDefinition;
import db.definitions.DatabaseDefinition;
import db.execute.Connect;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.DocumentException;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * The application's main frame.
 */
public class FeedBackView extends FrameView {

    private Connect con;
    private ConnectionProperties conProp = new ConnectionProperties();
    private String schema;
    private ArrayList<ColumnDefinition> objectPks = new ArrayList<ColumnDefinition>();
    private ArrayList<ColumnDefinition> usersPks = new ArrayList<ColumnDefinition>();
    private NewConnectionDialog newConnection;

    public FeedBackView(SingleFrameApplication app) {
        super(app);
        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                } else if ("done".equals(propertyName)) {
                    //busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                }
            }
        });
        this.getFrame().setResizable(false);
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = FeedBackApp.getApplication().getMainFrame();
            aboutBox = new FeedBackAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        FeedBackApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        objectsTableComboBox = new javax.swing.JComboBox();
        schemyComboBox = new javax.swing.JComboBox();
        previewButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        usersTableComboBox = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        defaultUserTextField = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        defaultPasswordTextField = new javax.swing.JTextField();
        loadConfigButton = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        schemaNameTextField = new javax.swing.JTextField();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        newConnectionMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();

        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setRequestFocusEnabled(false);

        objectsTableComboBox.setName("objectsTableComboBox"); // NOI18N
        objectsTableComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                objectsTableComboBoxActionPerformed(evt);
            }
        });

        schemyComboBox.setName("schemyComboBox"); // NOI18N
        schemyComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                schemyComboBoxItemStateChanged(evt);
            }
        });

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(feedback.FeedBackApp.class).getContext().getResourceMap(FeedBackView.class);
        previewButton.setText(resourceMap.getString("previewButton.text")); // NOI18N
        previewButton.setName("previewButton"); // NOI18N
        previewButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                previewButtonActionPerformed(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        usersTableComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<none>" }));
        usersTableComboBox.setName("usersTableComboBox"); // NOI18N
        usersTableComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                usersTableComboBoxActionPerformed(evt);
            }
        });

        jLabel4.setFont(resourceMap.getFont("jLabel4.font")); // NOI18N
        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        defaultUserTextField.setText(resourceMap.getString("defaultUserTextField.text")); // NOI18N
        defaultUserTextField.setName("defaultUserTextField"); // NOI18N

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        defaultPasswordTextField.setText(resourceMap.getString("defaultPasswordTextField.text")); // NOI18N
        defaultPasswordTextField.setName("defaultPasswordTextField"); // NOI18N

        loadConfigButton.setText(resourceMap.getString("loadConfigButton.text")); // NOI18N
        loadConfigButton.setName("loadConfigButton"); // NOI18N
        loadConfigButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadConfigButtonActionPerformed(evt);
            }
        });

        jLabel7.setFont(resourceMap.getFont("jLabel7.font")); // NOI18N
        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel8.setName("jLabel8"); // NOI18N

        schemaNameTextField.setText(resourceMap.getString("schemaNameTextField.text")); // NOI18N
        schemaNameTextField.setName("schemaNameTextField"); // NOI18N
        schemaNameTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                schemaNameTextFieldKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(usersTableComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(objectsTableComboBox, 0, 156, Short.MAX_VALUE))
                                    .addComponent(schemyComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 47, Short.MAX_VALUE))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(previewButton)
                            .addComponent(jLabel7)
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(schemaNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addGap(26, 26, 26)
                                .addComponent(loadConfigButton, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel4)
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel5))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(defaultPasswordTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE)
                                    .addComponent(defaultUserTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                .addContainerGap())
        );

        mainPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {objectsTableComboBox, schemyComboBox, usersTableComboBox});

        mainPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {defaultPasswordTextField, defaultUserTextField});

        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(schemyComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(objectsTableComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(usersTableComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(35, 35, 35)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel8)
                            .addComponent(schemaNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(39, 39, 39)
                        .addComponent(previewButton))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(defaultUserTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(defaultPasswordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(13, 13, 13)
                        .addComponent(loadConfigButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        newConnectionMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        newConnectionMenuItem.setText(resourceMap.getString("newConnectionItem.text")); // NOI18N
        newConnectionMenuItem.setToolTipText(resourceMap.getString("newConnectionItem.toolTipText")); // NOI18N
        newConnectionMenuItem.setName("newConnectionItem"); // NOI18N
        newConnectionMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newConnectionMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(newConnectionMenuItem);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(feedback.FeedBackApp.class).getContext().getActionMap(FeedBackView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setForeground(resourceMap.getColor("statusMessageLabel.foreground")); // NOI18N
        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 306, Short.MAX_VALUE)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents
    private void newConnectionMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newConnectionMenuItemActionPerformed
        // TODO add your handling code here:
        JFrame mainFrame = FeedBackApp.getApplication().getMainFrame();
        newConnection = new NewConnectionDialog(mainFrame, true);
        newConnection.setLocationRelativeTo(mainFrame);
        newConnection.setVisible(true);

        if (newConnection.isLoaded()) {
            conProp.setUsername(newConnection.getUsername());
            conProp.setPassword(newConnection.getPassword());
            conProp.setDatabaseName(newConnection.getDatabaseName());
            conProp.setHost(newConnection.getHost());

            schemyComboBox.removeAllItems();
            try {
                con = new Connect(conProp);
                if (!con.displaySchemas().isEmpty()) {
                    for (String schemaCon : con.displaySchemas()) {
                        if (validSchemaName(schemaCon)) {
                            schemyComboBox.addItem(schemaCon);
                        }
                    }
                    ArrayList<String> tables = con.displayTables(schemyComboBox.getSelectedItem().toString());
                    objectsTableComboBox.removeAllItems();
                    if (!tables.isEmpty()) {
                        for (String table : tables) {
                            objectsTableComboBox.addItem(table);
                        }
                        statusMessageLabel.setText("");
                    } else {
                        statusMessageLabel.setText("No tables in schema!");
                    }
                } else {
                    statusMessageLabel.setText("No schemas in database!");
                }
            } catch (SQLException ex) {
                Logger.getLogger(FeedBackView.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(FeedBackView.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
}//GEN-LAST:event_newConnectionMenuItemActionPerformed

    /**
     * if schema was selected, selectboxes for objects and users are filled with corresponding tables
     * @param evt
     */
    private void schemyComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_schemyComboBoxItemStateChanged
        if (schemyComboBox.getSelectedItem() != null) {
            try {
                busyIconTimer.start();
                schema = schemyComboBox.getSelectedItem().toString();
                objectsTableComboBox.removeAllItems();
                usersTableComboBox.removeAllItems();
                usersTableComboBox.addItem("<none>");
                ArrayList<String> tables = con.displayTables(schemyComboBox.getSelectedItem().toString());
                objectsTableComboBox.removeAllItems();
                if (!tables.isEmpty()) {
                    for (String table : tables) {
                        objectsTableComboBox.addItem(table);
                        usersTableComboBox.addItem(table);
                    }
                    statusMessageLabel.setText("");
                } else {
                    statusMessageLabel.setText("No tables in schema!");
                }
            } catch (SQLException ex) {
                Logger.getLogger(FeedBackView.class.getName()).log(Level.SEVERE, null, ex);
            }
            busyIconTimer.stop();
        }
    }//GEN-LAST:event_schemyComboBoxItemStateChanged

    /**
     * opens up a windows with generated sql code
     * @param evt
     */
    private void previewButtonActionPerformed(java.awt.event.ActionEvent evt) {
        if (canProceed(false)) {
            try {
                JFrame mainFrame = FeedBackApp.getApplication().getMainFrame();
                PreviewSQL preview = new PreviewSQL(mainFrame, true);
                preview.setConnection(con);
                XmlConfig xmlConfig = new XmlConfig();
                xmlConfig.setSchema_name(schemaNameTextField.getText());
                xmlConfig.setUsername(defaultUserTextField.getText());
                xmlConfig.setPassword(defaultPasswordTextField.getText());
                xmlConfig.setTable_objects(objectsTableComboBox.getSelectedItem().toString());
                xmlConfig.setTable_users(usersTableComboBox.getSelectedItem().toString().equals("<none>") ? "" : usersTableComboBox.getSelectedItem().toString());
                xmlConfig.setTable_objects_pks(objectPks);
                xmlConfig.setTable_users_pks(usersPks);
                xmlConfig.setTables_schema(schemyComboBox.getSelectedItem().toString());

                //TODO: nacitat vsetko potrebne
                xmlConfig.saveConfig();


                XmlModul xmlModul = new XmlModul();
                busyIconTimer.start();
                String sql = xmlModul.getSQL();
                preview.setPreviewText(sql);

                for (int i = DatabaseDefinition.SQL_FIRST - 1; i < DatabaseDefinition.SQL_LAST; i++) {
                    preview.getPartsOfSql()[i] = xmlModul.getSql(i);
                }
                
                preview.setVisible(true);
                busyIconTimer.stop();
            } catch (DocumentException ex) {
                Logger.getLogger(FeedBackView.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(FeedBackView.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * if objects table was selected, fill array objectPks with primary keys of selected table
     * @param evt
     */
    private void objectsTableComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_objectsTableComboBoxActionPerformed
        try {
            objectPks.clear();
            Object tabulka = objectsTableComboBox.getSelectedItem();
            if (tabulka != null && !tabulka.toString().equals("")) {//GEN-LAST:event_objectsTableComboBoxActionPerformed
                for (ColumnDefinition pk : con.getPK(null, schema, tabulka.toString())) {
                    objectPks.add(pk);
                }
            } else {
                objectPks.clear();
            }
        } catch (SQLException ex) {
            Logger.getLogger(FeedBackView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * if users table was selected, fill array objectPks with primary keys of selected table
     * @param evt
     */
    private void usersTableComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_usersTableComboBoxActionPerformed
        try {
            usersPks.clear();
            Object tabulka = usersTableComboBox.getSelectedItem();
            if (tabulka != null && !tabulka.equals("<none>")) {
                defaultUserTextField.setEnabled(false);
                defaultPasswordTextField.setEnabled(false);
            } else {
                defaultUserTextField.setEnabled(true);
                defaultPasswordTextField.setEnabled(true);
            }
            if (tabulka != null && !tabulka.toString().equals("") && !tabulka.toString().equals("<none>")) {
                for (ColumnDefinition pk : con.getPK(null, schema, tabulka.toString())) {
                    usersPks.add(pk);
                }
            } else {
                usersPks.clear();
            }
        } catch (SQLException ex) {
        //Logger.getLogger(FeedBackView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_usersTableComboBoxActionPerformed

    /**
     * checks if schema name already exists in database
     * @param evt
     */
    private void schemaNameTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_schemaNameTextFieldKeyReleased
        validNewSchemaName(schemaNameTextField.getText().trim());
    }//GEN-LAST:event_schemaNameTextFieldKeyReleased

    private void loadConfigButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadConfigButtonActionPerformed
        if (canProceed(true)) {
            try {
                JFrame mainFrame = FeedBackApp.getApplication().getMainFrame();
                PreviewSQL preview = new PreviewSQL(mainFrame, true);
                preview.setConnection(con);
                XmlModul xmlModul = new XmlModul();
                busyIconTimer.start();
                String sql = xmlModul.getSQL();
                preview.setPreviewText(sql);

                for (int i = DatabaseDefinition.SQL_FIRST - 1; i < DatabaseDefinition.SQL_LAST; i++) {
                    preview.getPartsOfSql()[i] = xmlModul.getSql(i);
                }

                preview.setVisible(true);
                busyIconTimer.stop();
            } catch (DocumentException ex) {
                Logger.getLogger(FeedBackView.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(FeedBackView.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

}//GEN-LAST:event_loadConfigButtonActionPerformed

    private boolean validSchemaName(String schema) {
        return schema.equals("information_schema") || schema.startsWith("pg_") || schema.equals("") ? false : true;
    }

    private boolean validTableName(String table) {
        return table.equals("") ? false : true;
    }

    private boolean validNewSchemaName(String schema) {
        if (!validSchemaName(schema)) {
//            Logger.getAnonymousLogger().log(Level.WARNING, "Schema must have a name!");
            statusMessageLabel.setText("Please rename the schema!");
            return false;
        }
        for (int i = 0; i < schemyComboBox.getItemCount(); i++) {
            String s = schemyComboBox.getItemAt(i).toString();
            if (schema.equals(s)) {
//                Logger.getAnonymousLogger().log(Level.WARNING, "Schema with this name already exists!");
                statusMessageLabel.setText("Schema with this name already exists!");
                return false;
            }
        }
        statusMessageLabel.setText("");
        return true;
    }

    private boolean canProceed(boolean config) {
        String err = "";
        boolean canProceed = true;
        if (con == null) {
            canProceed = false;
            err += "No connection loaded!\n";
        }
        if (!config) {
            if (!validSchemaName(schemaNameTextField.getText().trim())) {
                canProceed = false;
                err += "Not valid schema for tables of objects and users!\n";
            }
            if (objectsTableComboBox.getSelectedItem() == null || !validTableName(objectsTableComboBox.getSelectedItem().toString().trim())) {
                canProceed = false;
                err += "Not valid table for objects!\n";
            }
            if (usersTableComboBox.getSelectedItem() == null || !validTableName(usersTableComboBox.getSelectedItem().toString().trim())) {
                canProceed = false;
                err += "Not valid table for users - select one or <none>!\n";
            }
            if (!validNewSchemaName(schemaNameTextField.getText().trim())) {
                canProceed = false;
                err += "Not valid new schema name!\n";
            }
            if ((usersTableComboBox.getSelectedItem() != null && usersTableComboBox.getSelectedItem().toString().trim().equals("<none>")) && 
                (defaultUserTextField.getText().trim().equals("") || defaultPasswordTextField.getText().trim().equals("")) ) {
                canProceed = false;
                err += "Not valid default username or password!";
            }
        }
        if (!canProceed) {
            JOptionPane.showMessageDialog(null, err, "Error", JOptionPane.ERROR_MESSAGE);
        }
        return canProceed;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField defaultPasswordTextField;
    private javax.swing.JTextField defaultUserTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JButton loadConfigButton;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem newConnectionMenuItem;
    private javax.swing.JComboBox objectsTableComboBox;
    private javax.swing.JButton previewButton;
    private javax.swing.JTextField schemaNameTextField;
    private javax.swing.JComboBox schemyComboBox;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JComboBox usersTableComboBox;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
}
